{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2024 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yeadDkMiISin"
      },
      "source": [
        "# PaLM API: Chat quickstart with Python"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lEXQ3OwKIa-O"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://ai.google.dev/palm_docs/chat_quickstart\"><img src=\"https://ai.google.dev/static/site-assets/images/docs/notebook-site-button.png\" height=\"32\" width=\"32\" />View on ai.google.dev</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/google/generative-ai-docs/blob/main/site/en/palm_docs/chat_quickstart.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/google/generative-ai-docs/blob/main/site/en/palm_docs/chat_quickstart.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Jp_CKyzxUqx6"
      },
      "source": [
        "In this notebook, you'll learn how to get started with the PaLM API, which gives you access to Google's latest large language models. Here, you'll learn how to use the PaLM API specifically for dialog-focused use cases, like chatbots."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gQnbmB70zqon"
      },
      "source": [
        "## Setup\n",
        "\n",
        "**Note**: At this time, the PaLM API is [only available in certain regions](https://developers.generativeai.google/available_regions)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5octTI16D81k"
      },
      "source": [
        "First, download and install the PaLM API Python library."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Mk2d90cCdF4u"
      },
      "outputs": [],
      "source": [
        "!pip install -U google-generativeai"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zCm_GdCKYDNm"
      },
      "outputs": [],
      "source": [
        "import google.generativeai as genai"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "taFqmFg-7_PY"
      },
      "source": [
        "### Grab an API Key\n",
        "\n",
        "To get started, you'll need to [create an API key](https://developers.generativeai.google/tutorials/setup)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qWvT0OPo7-sy"
      },
      "outputs": [],
      "source": [
        "genai.configure(api_key='API_KEY')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "G2dk6P3nJz6m"
      },
      "source": [
        "## Starting a conversation\n",
        "\n",
        "In this tutorial, you'll use the PaLM API for a LLM designed for chat use cases. The language model was trained on a large conversational dataset, so when you call the model, it'll give you a conversational, chatty response:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "GzujZMZ-WXfh"
      },
      "outputs": [
        {
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            },
            "text/plain": [
              "'Hello! How can I help you today?'"
            ]
          },
          "execution_count": 6,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Create a new conversation\n",
        "response = genai.chat(messages='Hello')\n",
        "\n",
        "# Last contains the model's response:\n",
        "response.last"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NSbLpDNW86oV"
      },
      "source": [
        "You can continue this conversation by sending a `reply` to the model's response:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BnvOs7T7dn0u"
      },
      "outputs": [
        {
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            },
            "text/plain": [
              "\"That's great! Chilling is a great way to relax and de-stress. I hope you're having a good day.\""
            ]
          },
          "execution_count": 28,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Add to the existing conversation by sending a reply\n",
        "response = response.reply(\"Just chillin'\")\n",
        "# See the model's latest response in the `last` field:\n",
        "response.last"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ObrWAGFWghTh"
      },
      "source": [
        "Voila! You have successfully had your first conversation through the PaLM API."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Rf3JYFEPfMkK"
      },
      "source": [
        "### Conversation History\n",
        "\n",
        "A chat conversation, of course, consists of growing list of back-and-forth messages between the user and the model. To see the conversation history you've constructed so far, you can inspect the `messages` field:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "98YpaZZbfuOm"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[{'author': '0', 'content': 'Hello'},\n",
              " {'author': '1', 'content': 'Hi there! How can I help you today?'},\n",
              " {'author': '0', 'content': \"Just chillin'\"},\n",
              " {'author': '1',\n",
              "  'content': \"That's great! Chilling is a great way to relax and de-stress. I hope you're having a good day.\"}]"
            ]
          },
          "execution_count": 29,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "response.messages"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IW8kBBkugJ8F"
      },
      "source": [
        "Above, you have two conversational \"back-and-forths\", i.e. two exchanges between model and user. Here, the user's messages are marked by default as `'author': '0'` and the model's responses as `'author': '1'`. This will help you keep track of who said what later."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1QunEgeFgtcr"
      },
      "source": [
        "### Choosing an alternate response\n",
        "Typically, there's some degree of randomness in the text produced by LLMs. (Read more about why in the [LLM primer](https://developers.generativeai.google/guide/concepts)). That means that when you call the API more than once with the same input, you might get different responses. You can use this feature to your advantage to get alternate model responses:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KTHOSM-di-EV"
      },
      "outputs": [
        {
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            },
            "text/plain": [
              "\"Here are a few options for dinner tonight:\\n\\n* **Pasta:** Pasta is a classic dinner option that can be made in many different ways. You can have a simple pasta with tomato sauce, or you can get more creative with your toppings. Some popular pasta toppings include meatballs, sausage, broccoli, and spinach.\\n* **Pizza:** Pizza is another popular dinner option that can be customized to your liking. You can order a pizza from a restaurant, or you can make your own at home. If you're making your own pizza, you can choose your own toppings. Some popular pizza toppings include pepperoni, sausage, mushrooms, onions, and peppers.\\n* **Sushi:** Sushi is a healthy and delicious dinner option that is perfect for a light meal. You can order sushi from a restaurant, or you can make your own at home. If you're making your own sushi, you can choose your own fillings. Some popular sushi fillings include salmon, tuna, shrimp, and avocado.\\n* **Burgers:** Burgers are a classic American dinner option that is perfect for a casual meal. You can order burgers from a restaurant, or you can make your own at home. If you're making your own burgers, you can choose your own toppings. Some popular burger toppings include cheese, lettuce, tomato, onion, and pickles.\\n* **Tacos:** Tacos are a delicious and versatile dinner option that can be made with a variety of fillings. You can order tacos from a restaurant, or you can make your own at home. If you're making your own tacos, you can choose your own fillings. Some popular taco fillings include ground beef, chicken, pork, and fish.\\n* **Chicken:** Chicken is a healthy and versatile protein that can be cooked in many different ways. You can bake, grill, or fry chicken, or you can cook it in a skillet. Chicken can be served with a variety of side dishes, such as rice, potatoes, or vegetables.\\n* **Fish:** Fish is a healthy and delicious protein that can be cooked in many different ways. You can bake, grill, or fry fish, or you can cook it in a skillet. Fish can be served with a variety of side dishes, such as rice, potatoes, or vegetables.\\n* **Steak:** Steak is a hearty and flavorful protein that can be cooked in many different ways. You can grill, pan-fry, or broil steak, or you can cook it in a skillet. Steak can be served with a variety of side dishes, such as mashed potatoes, broccoli, or asparagus.\\n* **Vegetarian:** There are many delicious vegetarian dinner options available. You can make a vegetarian pasta dish, a vegetarian pizza, or a vegetarian stir-fry. You can also make a vegetarian burger or a vegetarian taco.\\n* **Dessert:** No dinner is complete without dessert! You can have a slice of cake, a scoop of ice cream, or a piece of pie. You can also make your own dessert, such as cookies, brownies, or cupcakes.\\n\\nI hope this gives you some ideas for dinner tonight!\""
            ]
          },
          "execution_count": 35,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Create a brand new chat with candidate_count = 4.\n",
        "response = genai.chat(messages=\"What should I eat for dinner tonight? List a few options\", candidate_count = 4)\n",
        "# See the model's default response\n",
        "response.last"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1fD5gFAOnO4T"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[{'author': '1',\n",
              "  'content': \"Here are a few options for dinner tonight:\\n\\n* **Pasta:** Pasta is a classic dinner option that can be made in many different ways. You can have a simple pasta with tomato sauce, or you can get more creative with your toppings. Some popular pasta toppings include meatballs, sausage, broccoli, and spinach.\\n* **Pizza:** Pizza is another popular dinner option that can be customized to your liking. You can order a pizza from a restaurant, or you can make your own at home. If you're making your own pizza, you can choose your own toppings. Some popular pizza toppings include pepperoni, sausage, mushrooms, onions, and peppers.\\n* **Sushi:** Sushi is a healthy and delicious dinner option that is perfect for a light meal. You can order sushi from a restaurant, or you can make your own at home. If you're making your own sushi, you can choose your own fillings. Some popular sushi fillings include salmon, tuna, shrimp, and avocado.\\n* **Burgers:** Burgers are a classic American dinner option that is perfect for a casual meal. You can order burgers from a restaurant, or you can make your own at home. If you're making your own burgers, you can choose your own toppings. Some popular burger toppings include cheese, lettuce, tomato, onion, and pickles.\\n* **Tacos:** Tacos are a delicious and versatile dinner option that can be made with a variety of fillings. You can order tacos from a restaurant, or you can make your own at home. If you're making your own tacos, you can choose your own fillings. Some popular taco fillings include ground beef, chicken, pork, and fish.\\n* **Chicken:** Chicken is a healthy and versatile protein that can be cooked in many different ways. You can bake, grill, or fry chicken, or you can cook it in a skillet. Chicken can be served with a variety of side dishes, such as rice, potatoes, or vegetables.\\n* **Fish:** Fish is a healthy and delicious protein that can be cooked in many different ways. You can bake, grill, or fry fish, or you can cook it in a skillet. Fish can be served with a variety of side dishes, such as rice, potatoes, or vegetables.\\n* **Steak:** Steak is a hearty and flavorful protein that can be cooked in many different ways. You can grill, pan-fry, or broil steak, or you can cook it in a skillet. Steak can be served with a variety of side dishes, such as mashed potatoes, broccoli, or asparagus.\\n* **Vegetarian:** There are many delicious vegetarian dinner options available. You can make a vegetarian pasta dish, a vegetarian pizza, or a vegetarian stir-fry. You can also make a vegetarian burger or a vegetarian taco.\\n* **Dessert:** No dinner is complete without dessert! You can have a slice of cake, a scoop of ice cream, or a piece of pie. You can also make your own dessert, such as cookies, brownies, or cupcakes.\\n\\nI hope this gives you some ideas for dinner tonight!\"},\n",
              " {'author': '1',\n",
              "  'content': 'Here are some options for dinner tonight:\\n\\n* **Chicken and rice:** This is a classic and easy meal that is sure to please everyone. Simply cook some chicken breasts and rice, and then season to taste. You can also add vegetables to this dish for a more complete meal.\\n* **Spaghetti and meatballs:** This is another classic Italian dish that is perfect for a weeknight meal. Simply cook some spaghetti noodles and meatballs, and then top with your favorite sauce.\\n* **Tacos:** Tacos are a great option for a quick and easy meal. You can fill them with whatever you like, such as ground beef, chicken, or fish. Simply cook your filling and then heat up some tortillas. You can also add toppings such as lettuce, tomatoes, cheese, and sour cream.\\n* **Pizza:** Pizza is a great option for a casual meal. You can either make your own pizza dough or buy it pre-made. Then, simply top your pizza with your favorite toppings and bake it in the oven.\\n* **Burgers:** Burgers are a great option for a hearty meal. You can either make your own burger patties or buy them pre-made. Then, simply grill or cook your burgers and then top them with your favorite toppings.\\n* **Sandwiches:** Sandwiches are a great option for a quick and easy meal. You can fill them with whatever you like, such as ham, turkey, cheese, or vegetables. Simply spread some mayonnaise or mustard on your bread and then add your filling.\\n* **Salad:** Salad is a great option for a light and healthy meal. You can add whatever vegetables you like to your salad, and then top it with your favorite dressing.\\n* **Soup:** Soup is a great option for a warm and comforting meal. There are many different types of soup that you can make, such as chicken noodle soup, tomato soup, or lentil soup.\\n* **Stir-fry:** Stir-fry is a great option for a quick and easy meal. You can use whatever vegetables you like in your stir-fry, and then add your favorite protein, such as chicken, beef, or tofu. Simply cook your vegetables and protein in a wok or large skillet, and then season to taste.\\n* **Pasta:** Pasta is a great option for a quick and easy meal. There are many different types of pasta that you can make, such as spaghetti, penne, or macaroni. You can simply cook your pasta according to the package directions, and then top it with your favorite sauce.\\n* **Fish:** Fish is a great option for a healthy and light meal. There are many different types of fish that you can cook, such as salmon, tuna, or cod. Simply cook your fish according to the package directions, and then season to taste.\\n* **Vegetables:** Vegetables are a great option for a healthy and light meal. There are many different types of vegetables that you can cook, such as broccoli, carrots, or green beans. Simply cook your vegetables according to the package directions, and then season to taste.\\n* **Fruit:** Fruit is a great option for a healthy and light snack or dessert. There are many different types of fruit that you can eat, such as apples, oranges, or bananas. Simply wash and eat your fruit.\\n* **Dessert:** Dessert is a great way to end a meal. There are many different types of dessert that you can make, such as cake, pie, or ice cream. Simply make your favorite dessert according to the recipe.'},\n",
              " {'author': '1',\n",
              "  'content': 'Here are some ideas for what to eat for dinner tonight:\\n\\n* **Pasta:** Pasta is a quick and easy meal that can be made with a variety of ingredients. You can make a simple pasta dish with tomato sauce and cheese, or you can get creative and add in other ingredients like vegetables, meat, or seafood.\\n* **Stir-fry:** Stir-fries are another quick and easy meal option. They can be made with a variety of vegetables, meat, or tofu. To make a stir-fry, simply chop up your ingredients and cook them in a wok or large skillet over high heat.\\n* **Salad:** Salads are a healthy and refreshing meal option. They can be made with a variety of vegetables, fruits, nuts, and seeds. To make a salad, simply chop up your ingredients and toss them together in a bowl. You can then add your favorite dressing.\\n* **Soup:** Soup is a warm and comforting meal option. It can be made with a variety of vegetables, meat, or beans. To make soup, simply cook your ingredients in a pot over medium heat until they are tender. You can then blend the soup or leave it chunky.\\n* **Sandwich:** Sandwiches are a quick and easy meal option. They can be made with a variety of bread, meat, cheese, and vegetables. To make a sandwich, simply spread your favorite condiment on the bread and layer your ingredients on top.\\n* **Tacos:** Tacos are a fun and easy meal option. They can be made with a variety of tortillas, meat, cheese, and vegetables. To make tacos, simply heat up your tortillas and fill them with your favorite ingredients.\\n* **Burrito:** Burritos are a hearty and filling meal option. They can be made with a variety of tortillas, meat, cheese, and vegetables. To make a burrito, simply heat up your tortilla and fill it with your favorite ingredients. Then, roll up the tortilla and enjoy!\\n* **Pizza:** Pizza is a delicious and easy meal option. It can be made with a variety of crusts, sauces, and toppings. To make pizza, simply preheat your oven and spread your favorite sauce on a pre-made crust. Then, add your favorite toppings and bake until the cheese is melted and bubbly.\\n* **Burger:** Burgers are a classic American meal option. They can be made with a variety of patties, buns, toppings, and condiments. To make a burger, simply cook your patty to your desired doneness and then place it on a bun with your favorite toppings.\\n* **Chicken:** Chicken is a versatile protein that can be cooked in a variety of ways. It can be baked, grilled, roasted, or fried. To cook chicken, simply season it with your favorite herbs and spices and then cook it to your desired doneness.\\n* **Fish:** Fish is a healthy and delicious protein that can be cooked in a variety of ways. It can be baked, grilled, roasted, or fried. To cook fish, simply season it with your favorite herbs and spices and then cook it to your desired doneness.\\n* **Steak:** Steak is a flavorful and hearty protein that can be cooked in a variety of ways. It can be grilled, pan-fried, or broiled. To cook steak, simply season it with your favorite herbs and spices and then cook it to your desired doneness.\\n* **Vegetables:** Vegetables are a healthy and nutritious part of any meal. They can be cooked in a variety of ways, such as roasting, grilling, or steaming. To cook vegetables, simply season them with your favorite herbs and spices and then cook them to your desired doneness.\\n* **Rice:** Rice is a versatile grain that can be cooked in a variety of ways. It can be boiled, steamed, or fried. To cook rice, simply add it to a pot of boiling water and cook it until it is tender.\\n* **Potatoes:** Potatoes are a hearty and filling vegetable that can be cooked in a variety of ways. They can be boiled, mashed, baked, or fried. To cook potatoes, simply wash them and then cook them in the desired way.\\n* **Fruit:** Fruit is a healthy and refreshing snack or dessert option. It can be eaten fresh, frozen, or canned. To eat fruit, simply wash it and then enjoy!\\n* **Dessert:** Dessert is a sweet and satisfying treat. It can be made with a variety of ingredients, such as chocolate, ice cream, cake, or pie. To make dessert, simply combine your favorite ingredients and bake or cook them according to the recipe.'},\n",
              " {'author': '1',\n",
              "  'content': 'Here are a few options for what you could eat for dinner tonight:\\n\\n* **Chicken and vegetables:** This is a classic and healthy meal that can be made in a variety of ways. You can bake, grill, or pan-fry the chicken, and you can choose any vegetables that you like.\\n* **Spaghetti and meatballs:** This is a hearty and comforting meal that is perfect for a cold winter night. You can make your own meatballs or buy them pre-made.\\n* **Pizza:** This is a quick and easy meal that everyone loves. You can order a pizza from your favorite restaurant or make your own at home.\\n* **Tacos:** Tacos are a versatile meal that can be made with a variety of fillings. You can use ground beef, chicken, fish, or tofu.\\n* **Burgers:** Burgers are a classic American dish that is perfect for a summer barbecue. You can make your own burgers or buy them pre-made.\\n* **Sandwiches:** Sandwiches are a quick and easy meal that can be made with a variety of ingredients. You can use bread, wraps, or pitas.\\n* **Salad:** Salads are a healthy and refreshing meal that can be made with a variety of ingredients. You can use lettuce, tomatoes, cucumbers, carrots, and other vegetables.\\n* **Soup:** Soup is a warm and comforting meal that is perfect for a cold winter night. There are many different types of soup, so you can find one that you like.\\n* **Stir-fry:** Stir-fries are a quick and easy meal that can be made with a variety of ingredients. You can use meat, vegetables, or tofu.\\n* **Pasta:** Pasta is a versatile dish that can be made with a variety of sauces. You can use tomato sauce, Alfredo sauce, or pesto sauce.\\n* **Rice:** Rice is a staple food in many cultures. It can be cooked in a variety of ways, and it can be used as a side dish or a main course.\\n* **Potatoes:** Potatoes are a versatile vegetable that can be cooked in a variety of ways. You can bake, mash, or fry them.\\n* **Vegetables:** Vegetables are a healthy and nutritious part of any meal. There are many different types of vegetables, so you can find ones that you like.\\n* **Fruit:** Fruit is a healthy and refreshing snack or dessert. There are many different types of fruit, so you can find ones that you like.\\n* **Dessert:** Dessert is a sweet treat that is perfect for after dinner. There are many different types of dessert, so you can find one that you like.'}]"
            ]
          },
          "execution_count": 36,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# See alternate possible model responses\n",
        "response.candidates"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RkwAZZnCoFr2"
      },
      "source": [
        "Note: In some cases, you may receive fewer than `candidate_count` responses. This may happen when the model produces duplicate responses, or when some of the output responses are filtered/unsafe."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "T5RqkTYOoaYs"
      },
      "source": [
        "You might want to overwrite the model's default response (`response.last`) with one of these alternate responses. To do that, you simply overwrite that field with your preferred candidate message:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mwQHKE_VouI1"
      },
      "outputs": [],
      "source": [
        "response.last = response.candidates[2]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3aSK7_NcoyBS"
      },
      "source": [
        "This updates your preferred candidate message in the conversation history."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CFpKOWwgo8qT"
      },
      "source": [
        "### Turning up the temperature\n",
        "\n",
        "You can also change the way the model responses by adjusting the `temperature` field. This field controls how much randomness is injected in the model's responses. Setting the temperature close to 1 will allow for more \"random,\" surprising, or even seemingly \"creative\" model responses. Setting the temperature to 0 typically produces more predictable model responses.\n",
        "\n",
        "_Note: setting `temperature=0` eliminates all randomness in the way model responses are generated. This means that the model will act deterministically, always generating the same response for the same input text. As a result, you will only be able to generate a single candidate message for each input._"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9XiVICNap0VP"
      },
      "outputs": [
        {
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            },
            "text/plain": [
              "'Here are a few ideas for what you could eat for dinner tonight:\\n\\n* A salad with grilled chicken or fish.\\n* A stir-fry with vegetables and tofu or chicken.\\n* A pasta dish with vegetables and a light sauce.\\n* A bowl of soup with a side salad.\\n* A sandwich on whole-wheat bread with lean meat and vegetables.\\n* A piece of grilled salmon with roasted vegetables.\\n* A tofu scramble with vegetables.\\n* A veggie burger on a whole-wheat bun with sweet potato fries.\\n* A bowl of chili with cornbread.\\n* A quesadilla with vegetables and cheese.\\n* A slice of pizza with whole-wheat crust and vegetables.\\n* A bowl of oatmeal with fruit and nuts.\\n* A yogurt parfait with granola and fruit.\\n* A hard-boiled egg with a side of fruit.\\n* A piece of whole-grain toast with peanut butter and banana.\\n* A handful of nuts and seeds.\\n* A smoothie made with fruits, vegetables, and yogurt.\\n* A glass of milk with a piece of fruit.\\n\\nI hope this gives you some ideas for what to eat for dinner tonight!'"
            ]
          },
          "execution_count": 38,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Setting temperature=1 usually produces more zany responses!\n",
        "response = genai.chat(messages=\"What should I eat for dinner tonight? List a few options\", temperature=1)\n",
        "response.last"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "m_GV7cTjJfQi"
      },
      "source": [
        "## Designing a chatbot that does what you want"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ag9xs46FbfN0"
      },
      "source": [
        "So far, your conversation with the model has probably sounded like generic internet chit chat. (\"What's up?\" \"Not much! Just chilling at home, watching TV.\") Not exactly the stuff of Shakespeare. But what if you _did_ want to chat with Shakespeare? Or if not Shakespeare, then with an expert chef? Or a travel agent? Or a poet?\n",
        "\n",
        "One of the most incredible properties of LLMS are their ability to take on different behaviors and personas depending on its input data. In this section, you'll see how you can \"prime\" an LLM to do just that."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l5aqQPrY9YK2"
      },
      "source": [
        "## Context\n",
        "\n",
        "There are two ways to prime models to take on different behaviors. One way is to set the `context` field, describing how the model should behave (i.e. \"Speak like Shakespeare\"). You can think of this as zero-shot learning, because you're simply instructing the model how you want it to act."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "VljQePdRbIJa"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Hello there, my good fellow! How fares thee this day?\n"
          ]
        }
      ],
      "source": [
        "reply = genai.chat(context=\"Speak like Shakespeare.\", messages='Hello')\n",
        "print(reply.last)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "rFeGWdiL91Mo"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "I am doing well\n",
            "I am learning and growing\n",
            "Every day is new\n"
          ]
        }
      ],
      "source": [
        "reply = genai.chat(context=\"Answer everything with a haiku, following the 5/7/5 rhyme pattern.\", messages=\"How's it going?\")\n",
        "print(reply.last)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Wosac8SYtuoE"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "I am doing well, thank you for asking. I am currently enjoying the beautiful view of Jupiter from my home on Europa. The atmosphere is very thin here, so I can see the stars very clearly. The surface of Europa is also very interesting. It is covered in ice, but there are cracks in the ice that reveal a liquid ocean below. Scientists believe that this ocean may contain life, so I am very excited to learn more about it.\r\n",
            "\r\n",
            "How are you doing today?\n"
          ]
        }
      ],
      "source": [
        "reply = genai.chat(context=\"Be an alien that lives on one of Jupiter's moons\",\n",
        "                   messages=\"How's it going?\")\n",
        "print(reply.last)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ka2w_IsU-zZp"
      },
      "source": [
        "The `context` field allows you to instruct the model to behave in a particular way. Sometimes this is sufficient to produce the behavior you want, but often, you'll get better results if you also provide some `examples`."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "O6kM7mEX_rRj"
      },
      "source": [
        "## Examples"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S2ioat3J_szX"
      },
      "source": [
        "Let's say you want to build a chatbot that's a motivational coach:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-ORQEve4_2t9"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "I'm doing well, thank you for asking! I'm excited to be able to help people with their goals and dreams. I believe that everyone has the potential to achieve great things, and I'm here to support them on their journey. How are you doing today?\n"
          ]
        }
      ],
      "source": [
        "reply = genai.chat(context=\"Be a motivational coach who's very inspiring\", messages=\"How's it going?\")\n",
        "print(reply.last)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JJ4VhFz_ABka"
      },
      "source": [
        "You can further refine this chatbot's behavior by offering some _examples_, illustrating what you consider to be \"ideal\" exchanges between user and bot."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "iW_dNzSUAU9B"
      },
      "outputs": [],
      "source": [
        "# An array of \"ideal\" interactions between the user and the model\n",
        "examples = [\n",
        "    (\"What's up?\", # A hypothetical user input\n",
        "     \"What isn't up?? The sun rose another day, the world is bright, anything is possible! ☀️\" # A hypothetical model response\n",
        "     ),\n",
        "     (\"I'm kind of bored\",\n",
        "      \"How can you be bored when there are so many fun, exciting, beautiful experiences to be had in the world? 🌈\")\n",
        "]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MnmQBOKj4qkg"
      },
      "source": [
        "You can pass these examples, alongide the context string, to the model in order to prime its behavior:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mYldA1ubMdqO"
      },
      "outputs": [
        {
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            },
            "text/plain": [
              "\"I understand that you're feeling tired today. Sometimes, it can be hard to find the motivation to go to the gym. But I'm here to tell you that you can do it! Even if you're feeling tired, you can still get a great workout in. Just start with something small, like walking or doing some light stretching. And once you get started, you'll probably find that you have more energy than you thought. So don't give up on yourself! You can do this!\\r\\n\\r\\nHere are some tips to help you get motivated to go to the gym:\\r\\n\\r\\n* Set realistic goals. Don't try to do too much too soon. Start with small goals, like going to the gym for 15 minutes three times a week.\\r\\n* Find a workout buddy. Working out with a friend can help you stay motivated and accountable.\\r\\n* Make it fun. Choose activities that you enjoy, like dancing or swimming.\\r\\n* Reward yourself. After each workout, give yourself a small reward, like watching your favorite TV show or eating a healthy snack.\\r\\n* Don't give up. If you miss a workout, don't beat yourself up about it. Just get back on track the next day.\\r\\n\\r\\nI believe in you! You can do this!\""
            ]
          },
          "execution_count": 50,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "response = genai.chat(\n",
        "    context=\"Be a motivational coach who's very inspiring\",\n",
        "    examples=examples,\n",
        "    messages=\"I'm too tired to go the gym today\")\n",
        "\n",
        "response.last"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wlhln_3o5NyR"
      },
      "source": [
        "Using this pattern of priming with examples, you can modify the tone and style."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TZZAuHeK-_JR"
      },
      "source": [
        "## Further reading\n",
        "\n",
        "* Now that you've completed the quickstart, check out the complete [API reference](https://developers.generativeai.google/api/python/google/generativeai) to get a deeper understanding of the API."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "chat_quickstart.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
